package com.fw.controller;


import com.fw.entity.MyException;
import com.fw.entity.Result;
import com.fw.entity.User;
import com.fw.entity.Varifycode;
import com.fw.service.IUserService;
import com.fw.service.IVarifycodeService;
import com.fw.utils.JWTUtils;
import com.fw.utils.OSSUtil;
import com.fw.utils.RedisUtil;
import com.fw.utils.SendEmail;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author james
 * @since 2021-06-19
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private IVarifycodeService varifycodeService;
    @Resource
    private RedisUtil redisUtil;

    @RequestMapping("/login")
    public Result Login(@RequestParam String email,
                        @RequestParam String password)
            throws MyException {
        //邮箱密码不能为空
        if(email.equals(""))
            throw new MyException("邮箱不能为空", "010101");
        if(password.equals(""))
            throw new MyException("密码不能为空", "010102");

        //将邮箱存入map中，以map形式查找
        Map<String, Object> m = new HashMap<>();
        m.put("email", email);
        System.out.println(m);
        List<User> users = userService.listByMap(m);

        //没有这个邮箱对应的用户
        if(users.isEmpty())
            throw new MyException("该用户不存在，请检查输入邮箱", "010103");
        User user = users.get(0);
        //验证密码是否正确
        if(!user.getPassword().equals(password))
            throw new MyException("密码不正确，请重新输入", "010104");

        //存储token
        user.setPassword(null);
        String userId = user.getUid().toString();
        redisUtil.remove(userId);
        String token = JWTUtils.createToken(userId, 24 * 7 * 60 * 60L);
        redisUtil.set(userId, token, 24 * 7 * 60 * 60L);

        //返回数值
        user.setToken(token);
        return new Result(user, "登录成功", "000000");
    }


    @RequestMapping("/sendMail")
    public Result sendMail(String email
    ) throws MyException{
        if(email == ""){
            throw new MyException("邮箱不能为空","010201");
        }
        else if(!email.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*")){
            throw new MyException("邮箱格式错误","010202");
        }
        Varifycode varifycode = new Varifycode();
        //String uid = JWTUtils.getUserId(request.getHeader("token"));
        Map<String, Object> map = new HashMap<>();
        map.put("email",email);
        List<User> users = userService.listByMap(map);
        if(!users.isEmpty()){
            throw  new MyException("该邮箱已存在", "010203");
        }
        List<Varifycode> varifycodes = varifycodeService.listByMap(map);
        if(!varifycodes.isEmpty()){
            throw  new MyException("该邮箱已发送验证码", "010205");
        }
        Random random = new Random();
        int x = random.nextInt(899999);
        x = x+100000;
        String code = x+"";
        varifycode.setVarifycode(code);
        varifycode.setEmail(email);
        Date date = new Date();

        varifycode.setVtime(date);
        try{
            SendEmail.send_email(email,code);
        }catch (Exception ex){
            throw  new MyException("邮件发送失败,请重试", "010204");
        }
        varifycodeService.saveOrUpdate(varifycode);
        return new Result(null, "验证码已成功发送", "000000");
    }


    @RequestMapping("/register")
    public Result register(@RequestParam String email,
                           @RequestParam String password,
                           @RequestParam String uname,
                           @RequestParam String utype,
                           @RequestParam String varifycode)
            throws MyException, IOException {
        Date date1 = new Date();
        Map<String, Object> map = new HashMap<>();
        map.put("email",email);
        if(varifycodeService.listByMap(map).isEmpty()){
            throw new MyException("未向该邮箱发送过验证码","010301");
        }
        else{
            map.put("varifycode",varifycode);
            List<Varifycode> varifycodes = varifycodeService.listByMap(map);
            if(varifycodes.isEmpty()){
                throw new MyException("验证码错误","010304");
            }
            Varifycode nvarifycode = varifycodes.get(0);
            User user = new User();
            Date date2 = nvarifycode.getVtime();

            long minutes =(date1.getTime()-date2.getTime())/ (1000 * 60);
            if(email.equals("") || password.equals("") || uname.equals("") || utype.equals("") || varifycode.equals("")){
                throw new MyException("表单各数据项不能为空","010303");
            }
            else{
                if(uname.length() > 10)
                    throw new MyException("用户名称长度过长", "010305");
                if(password.length() > 16 && password.length() < 6)
                    throw new MyException("密码长度错误", "010306");
                if(minutes<=10){
                    user.setEmail(email);
                    user.setPassword(password);
                    user.setUname(uname);
                    user.setUtype(utype);
                    user.setUcreatedate(date1);
                    user.setUstate("2");
                    userService.saveOrUpdate(user);
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("email",email);
                    List<User> users2 = userService.listByMap(map2);
                    int uId = users2.get(0).getUid();
                    nvarifycode.setUid(uId);
                    varifycodeService.saveOrUpdate(nvarifycode);
                    String uid = uId+"";
                    String token = JWTUtils.createToken(uid, 24 * 7 * 60 * 60L);
                    redisUtil.set(uid, token, 24 * 7 * 60 * 60L);
                    try {
                        Addprofile(Integer.parseInt(uid));
                    }catch (MyException me){
                        throw new MyException("生成头像错误，请重试");
                    }
                    varifycodeService.removeByMap(map);

                    return new Result(userService.listByMap(map2).get(0),"注册成功","000000");
                }
                else{
                    varifycodeService.removeByMap(map);
                    throw new MyException("验证码过期","010302");
                }
            }
        }

    }

    @RequestMapping("/addRecord")
    public Result addRecord(HttpServletRequest request){
        String uid = JWTUtils.getUserId(request.getHeader("token"));
        Map<String, Object> map = new HashMap<>();
        map.put("uid",uid);
        User user = userService.listByMap(map).get(0);
        user.setUstate("1");
        userService.saveOrUpdate(user);
        return new Result(null,"审核成功","000000");
    }

    public void Addprofile(int uid) throws IOException, MyException {
        //判断uid是否有效
        Map<String, Object> m = new HashMap<>();
        m.put("uid",uid);
        List<User> users = userService.listByMap(m);
        if(users.isEmpty()){
            throw new MyException("uid无效","010306");
        }
        //Flie转MultipartFile
        //随机从10张图片中选取一张
        int random=(int)(Math.random()*10+1);
        String picpath = "C:/Users/11454/Desktop/picture/picture" + random +".jpg";
        File file = new File(picpath);
        String Uid ="userid"+ uid;
        FileInputStream inputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
        //上传、
        OSSUtil.uploadAvatar(Uid,multipartFile);
        Uid = Uid+".jpg";
        //获取uri
        String DownLoadUrl = OSSUtil.getDownLoadUrl(Uid);
        //存入数据库
        User user = users.get(0);
        user.setAvatar(DownLoadUrl);
        userService.saveOrUpdate(user);
    }
}